/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmcheckOut.java
 *
 * Created on 14-03-2011, 12:23:13
 */

package GUI;

import interact.DataInteraction;
import interact.ValidateData;
import interact.connect;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author UnderGround
 */
public class frmcheckOut extends javax.swing.JDialog {
        Vector vtCallnumber;// = new Vector();
        String code ="";
        DefaultTableModel dtm;
        frmSearch search;
        private frmSearch parentForm;
        public void setParentForm(frmSearch _f){
            this.parentForm = _f;
        }
    /** Creates new form frmcheckOut */
    public frmcheckOut(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    frmcheckOut(frmSearch aThis, boolean b,Vector callnumber) {
        initComponents();
        parentForm = aThis;
        search = aThis;
        vtCallnumber = callnumber;
//        System.out.println(vtCallnumber);
        for (int i= 0; i < vtCallnumber.size(); i++) {
             code += vtCallnumber.elementAt(i).toString()+"|";
        }
       dtm = DataInteraction.getBook_UserChooceToTable(code, tblBookUserChooce);
    }

//    public void loadTable(){
//         for (int i= 0; i < vtCallnumber.size(); i++) {
//             code += vtCallnumber.elementAt(i).toString()+"|";
//        }
//         System.out.println("code load"+code);
//        dtm = DataInteraction.getBook_UserChooceToTable(code, tblBookUserChooce);
//    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFormattedTextField1 = new javax.swing.JFormattedTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtUserId = new javax.swing.JTextField();
        txtUserName = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblBookUserChooce = new javax.swing.JTable(){
            public boolean isCellEditable(int rowIndex, int vColIndex) {
                return false;
            }
        };
        btnSave = new javax.swing.JButton();
        btnBack = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        btnRemove = new javax.swing.JButton();
        txtIssueDate = new com.toedter.calendar.JDateChooser();
        txtDueDate = new com.toedter.calendar.JDateChooser();

        jFormattedTextField1.setText("jFormattedTextField1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Student ID");

        jLabel2.setText("Student name");

        txtUserId.setEditable(false);

        txtUserName.setEditable(false);

        jLabel3.setText("Issue date");

        jLabel4.setText("Due date");

        tblBookUserChooce.setBackground(new java.awt.Color(255, 255, 204));
        tblBookUserChooce.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblBookUserChooce.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(tblBookUserChooce);

        btnSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.png"))); // NOI18N
        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnBack.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/go-back.png"))); // NOI18N
        btnBack.setText("Back");
        btnBack.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBackActionPerformed(evt);
            }
        });

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/select.png"))); // NOI18N
        jButton3.setText("choose");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/new.png"))); // NOI18N
        jButton4.setText("New ");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        btnRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/del.png"))); // NOI18N
        btnRemove.setText("Remove book");
        btnRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 584, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(180, 180, 180)
                .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnBack)
                .addContainerGap(224, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(119, 119, 119)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtDueDate, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)
                    .addComponent(txtIssueDate, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)
                    .addComponent(txtUserName, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE)
                    .addComponent(txtUserId, javax.swing.GroupLayout.DEFAULT_SIZE, 188, Short.MAX_VALUE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnRemove)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jButton4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addGap(29, 29, 29))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(jButton4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtUserId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3))
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtUserName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(26, 26, 26)
                        .addComponent(jLabel4)
                        .addGap(28, 28, 28)
                        .addComponent(btnRemove))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtIssueDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(txtDueDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnBack)
                    .addComponent(btnSave))
                .addGap(30, 30, 30))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-600)/2, (screenSize.height-527)/2, 600, 527);
    }// </editor-fold>//GEN-END:initComponents

    private void btnBackActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBackActionPerformed
        if(this.parentForm!=null){
            this.parentForm.loadTable();
           dispose();
        }
    }//GEN-LAST:event_btnBackActionPerformed

    private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
        String newCode ="";
        rowSelected = tblBookUserChooce.getSelectedRow();
        if(rowSelected == -1){
            ValidateData.showMessage("please choose book to remove");
            return;
        }
        else if(tblBookUserChooce.getSelectedRow() >= 0) {
            String value =  tblBookUserChooce.getValueAt(rowSelected, 1).toString();
            dtm.removeRow(tblBookUserChooce.getSelectedRow());
            vtCallnumber.removeElement(value);
            System.out.println("remove"+value);
            System.out.println(vtCallnumber);
            System.out.println(vtCallnumber.size());
            for (int i= 0; i < vtCallnumber.size(); i++) {
             newCode += vtCallnumber.elementAt(i).toString()+"|";
        }
            DataInteraction.getBook_UserChooceToTable(newCode, tblBookUserChooce);
        } 
        if(code.trim().equals("")){
           btnSave.setVisible(false); 
        }else{
        }
        
        
    }//GEN-LAST:event_btnRemoveActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        int userID;
         Date getIssueDate = null;
          Date getDueDate = null;
        try{
         getIssueDate =txtIssueDate.getDate();
        getDueDate =txtDueDate.getDate();
        }catch(Exception e){
            ValidateData.showMessage("Date invalid");
            return;
        }
        if(vtCallnumber.size()<=0){
            ValidateData.showMessage("<html>no books were selected <br> please back to select book<html>");
            return;
        }
        else if(txtUserId.getText().trim().equals("")) {
            ValidateData.showMessage("<html>Please choose a employee <br> or create new employee</html>");
            return;
        }else {
        userID = Integer.parseInt(txtUserId.getText());
        }
        for (int i = 0; i < tblBookUserChooce.getRowCount(); i++) {
                Vector temp = (Vector) dtm.getDataVector().elementAt(i);
                int BookID = Integer.parseInt(temp.elementAt(0).toString());
                int check =  DataInteraction.Check_status(BookID,userID);
                if(check>=1){
                 ValidateData.showMessage("you have borrowed books ID is "+BookID);
                 return;
             }
            }

         if(!ValidateData.checkDate(getIssueDate, getDueDate)){
            ValidateData.showMessage("Due date must be erlier issue date");
            return;
        }
        else {
            int empID = Integer.parseInt(txtUserId.getText().trim());
        String isue = ValidateData.convertDateToString(txtIssueDate.getDate());
        String due = ValidateData.convertDateToString(txtDueDate.getDate());
            String sql = "insert into tblIssueMaster(EmployeeID,IssueDate,DueDate,Status)"
                    + " values(" + empID + ",'" + isue + "','" + due + "','" + 1 + "')";
            try {
                Statement st2 = connect.conn.createStatement();
                st2.execute(sql);
            } catch (SQLException ex) {
                System.out.println("error !");
            }

            //get the latest value inserted into tblIssueMaster table
            int lastID = DataInteraction.getLastID();

            for (int i = 0; i < tblBookUserChooce.getRowCount(); i++) {
                Vector temp = (Vector) dtm.getDataVector().elementAt(i);
                int BookID = Integer.parseInt(temp.elementAt(0).toString());
                data = new Vector();
                data.add(lastID);
                data.add(BookID);
                DataInteraction.updateData("SaveTo_dboIssueDetails", data);
//                dispose();

            }
            if (this.parentForm != null) {
                this.parentForm.loadTable();
                dispose();
                   ValidateData.showMessage("add new  borrower successful");
            }
         
        }

        
    }//GEN-LAST:event_btnSaveActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        frmChooseEmployee choose = new frmChooseEmployee(this);
        choose.setModal(true);
        choose.setVisible(true);
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        frmAddEmployee add = new frmAddEmployee();
        add.setModal(true);
        add.setVisible(true);
    }//GEN-LAST:event_jButton4ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                frmcheckOut dialog = new frmcheckOut(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
private Vector data;
private int rowSelected,id;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBack;
    private javax.swing.JButton btnRemove;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblBookUserChooce;
    private com.toedter.calendar.JDateChooser txtDueDate;
    private com.toedter.calendar.JDateChooser txtIssueDate;
    protected static javax.swing.JTextField txtUserId;
    protected static javax.swing.JTextField txtUserName;
    // End of variables declaration//GEN-END:variables

}
